define(function(require, exports){
	var pubjs	= require('pubjs');
	var popwin	= require('@base/dialog').base;
	var $		= require('jquery');
	var util	= require('util');
	var dspUtil = require('dspUtil');

	var ChannelWin = popwin.extend({
		init:function(config){
			config = pubjs.conf(config, {
				"title": LANG("渠道"),
				"width": 600
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			this.Super('afterBuild',arguments);
			var el = this.getDOM('body');
			var cls = this.getConfig('class');
			el.addClass(cls);
			el.append($([
				'<div pub-name="channel" pub-mod="modules/checkBoxGroup.base"></div>'
			].join('')));

			var config = {
				'channel': {
					'class': 'P-infoWhiteList P-infoChannelWin',
					'items': pubjs.config('exchange'),
					'view_model': {
						'items': [],
						'id': 'id',
						'prefix': 'ch',
						'name': 'name'
					}
				}
			};

			this.buildFromTemplate(config);
		},
		afterBuildTemplate: function(){
		},
		onOk: function(){
			var ids = this.$.channel.getValue(true);
			if(ids && ids.length){
				this.fire('popwinSave', {
					Ids: ids,
					Index: this.$index
				});
			}
			this.hide();
			return false;
		},
		setData: function(index, data){
			this.$index = index;
			data = this._toNumber(data);
			this.$.channel.setValue(data);
			return this;
		},
		reset: function(){
			this.$index = null;
			this.$data = null;
			this.$.channel.reset();
			this.hide();
			return this;
		},
		_toNumber: function(data){
			var result = [];
			util.each(data, function(val,index){
				if(util.isNumber(val)){
					result.push(val.toString());
				}
			})
			return result;
		}
	});

	exports.channelWin = ChannelWin;

	// 广告位popwin
	var SpotWin = popwin.extend({
		init:function(config){
			config = pubjs.conf(config, {
				"title": LANG("广告位"),
				"width": 800,
				"class": 'P-infoSpotWin',
				"view_model": {
					"showSelected": this.eventChangeShowSelect
					,"selectValue": false
					//批量导入广告位
					,"eventImport": this.eventImport
					//批量导出广告位
					,"eventExport": this.eventExport
				},
				"urlCheck": "spot/rtbCheck"

			});
			this.$channel = null;

			this.Super('init', arguments);

			this.$index = null;	// 行索引
			this.$data = null;
		},
		afterBuild:function(){
			this.Super('afterBuild',arguments);
			var el = this.getDOM('body');
			var cls = this.getConfig('class');
			el.addClass(cls);
			//el.height(600);
			el.append($([
				'<div class="M-tagLabelsWrapper">',
					'<div pub-mod="@base/taglabels.listType" pub-name="channel" class="P-moreRuleSpotWin"></div>',
				'</div>',
				'<div class="spotCon">',
					'<div class="hasSelected">',
						'<label ms-click="showSelected(selectValue)">',
							'<input type="checkbox" ms-duplex-radio="selectValue"/>',
							LANG('显示已选'),
						'</label>',
					'</div>',
					'<div pub-name="grid" pub-mod="addAccount/grid/adPosition.base" ></div>',
					'<div class="mt20">',
						'<div ms-click="eventExport" class="btn btn-default mr5 fr">'+ LANG('批量导出') +'</div>',
						'<div ms-click="eventImport" class="btn btn-default mr15 fr">'+ LANG('批量导入') +'</div>',
					'</div>',
				'</div>'
			].join('')));

			// 设置第一个渠道位默认选项
			var exchange = util.clone(pubjs.config('exchange'));
			var defExchange;
			if (exchange && exchange[0])
			{
				this.$channel = defExchange = exchange[0].id;
				exchange[0].def = true;
			}

			var config = {
				'channel': {
					'collapse': true,
					'all_label':'',
					'title': LANG('渠道：'),
					'data': exchange
				},
				'grid': {
					'eventDataLoad': true,
					'param': {
						'ChannelId': defExchange
					}
				}
			};

			// 导入导出窗口
			this.createAsync('dialog', 'modules/importExport.base',
				{
					'noProcess': true
				}
			);

			this.buildFromTemplate(config);
		},
		afterBuildTemplate: function(){

		},
		onListTypeChange: function(ev){
			var grid = this.$.grid;
			switch(ev.name){
				case 'channel':
					this.$channel = ev.param.item.id;
					break;
			}
			grid.setParam({
				'ChannelId':this.$channel
			});
			grid.load();
			return false;
		},
		eventChangeShowSelect: function(value){
			if(value){
				var data = this.$.grid.getSelectRowIds();
				this.$.grid.setParam({
					'ids': data
				});
			}else{
				this.$.grid.setParam({
					'ids': null
				});
			}
			this.$.grid.load();
		},
		onOk:function(evt){
			var data = this.$.grid.getSelectRowIds();
			this.fire('popwinSave', {
				Ids: data,
				Index: this.$index
			});
			this.reset();
			return false;
		},
		renderSize: function(i,val,row,con){
			return row.Width+" x "+row.Height;
		},
		renderName: function(i,val,row,con){
			return $('<p class="M-tableListWidthLimit" />').width(380).text(val);
		},
		setData:function(index, data){
			this.$data = data;
			this.$index = index;
			this.$.grid.setSelectRowIds(data);
			//this.$.grid.setValue({
			//	"selects":data
			//});
			return this;
		},
		reset: function(){
			this.$index = null;
			this.$data = null;
			this.$.grid.setSelectRowIds([]);
			this.$.grid.reload(null, {'ids':null});
			this.$.channel.reset();
			this.hide();
			this.vm.reset();
			return this;
		},
		onGridDataLoad: function(ev){
			//if(this.$data){
			//	this.$.grid.setValue({
			//		"selects":this.$data
			//	});
			//}
		//	// 查看状态，不可选
		//	var c = this.getConfig();
		//	if(c.disabled){
		//		this.$.grid.getDOM().find('.M-tableList')
		//			.find('input[type="checkbox"]')
		//			.prop('disabled',true);
		//	}
		},
		eventImport: function()
		{
			this.$.dialog.setTitle(LANG('批量导入')).setData('').show();
		},
		eventExport: function()
		{
			var ids = this.$.grid.getSelectRowIds();
			this.$.dialog.setTitle(LANG('批量导出')).setData(ids.join('\n')).show();
		}
		,onImportList: function(ev){
			var self = this;
			var data = ev.param;
			data = data.split('\n');
			var importIds = [];

			util.each(data, function(id)
			{
				id = util.trim(id.split('\t').shift());
				if (id)
				{
					importIds.push(id);
				}
			});

			importIds = importIds.join(',');
			var param = {
				'ids': importIds,
				'ChannelId': this.$channel
			};

			if(importIds)
			{
				self.sendUrlCheck(param, ev.param)
			}
		}
		,sendUrlCheck: function(param, cbParam) {
			var self = this;
			if(self.$mcMid) {
				pubjs.mc.abort(self.$mcMid, true);
			}
			self.$mcMid = pubjs.mc.send(
				self.getConfig('urlCheck')
				,param
				,self.afterCheck.bind(self)
				,cbParam || {}
			);
		}
		,afterCheck: function(err, data, param) {
			var self = this;
			var error;
			if(err) {
				pubjs.error(err);
				return false;
			}

			//转换成字段串，做匹配
			dspUtil.map(data.compareIds || [], String);
			dspUtil.map(data.sysIds || [], String);

			// 过滤导入失败的广告位
			if(param) {
				error = [];
				util.each(param.list, function(id, index) {
					if(data.compareIds.indexOf(id) == -1) {
						error.push(param.lines[index]);
					}
				});
			}

			self.$ids = this.$.grid.getSelectRowIds() || [];

			var tmp = self.$ids.concat(data.sysIds);
			var ids = [];
			for(var i = 0; i < tmp.length; i++) {
				if(tmp.lastIndexOf(tmp[i]) == i && tmp[i]) {
					ids.push(tmp[i]);
				}
			}
			this.$.grid.setSelectRowIds(ids);

			if(error && error.length) {
				var con = $('<div><p>'+ LANG('以下这些记录导入失败') +'</p></span></div>');
				util.each(error, function(err) {
					con.append('<p>'+ err +'</p>');
				});
				pubjs.alert(con);
				return false;
			}

			return false;
		}
	});

	exports.spotWin = SpotWin;
});